<?php include('scripts.php');

?>
<script type="text/javascript">
var datagridOpenTransaction = null;
var datagridBuyingHistory = null;
var datagridSellingHistory = null;
$(function() {
    $("#tradingForm").validate({
        messages : {

        },
        rules : {

        },
        submitHandler: function(form) {
            waiting();
            var buyAmount = $('#txtBuyAmount').val();
            var ecashBalance = $('#txtTradingPoint').val();

            if (parseFloat(buyAmount) == 0) {
                alert("<?php echo __('Quantity to buy cannot be zero', null, "goldTrading") ?>.");
                $("#txtBuyAmount").focus().select();
                return false;
            }
            var currentGoldPrice = $("#spanGoldSell").html();
            var totalAmount = Math.ceil(currentGoldPrice * buyAmount * 100) / 100;

            if (parseFloat(ecashBalance) < (parseFloat(totalAmount))) {
                alert("<?php echo __("In-sufficient Trading Point")?>" + "<br><?php echo __('Trading Margin Required', null, "goldTrading") ?>:" + totalAmount);
                return false;
            }

            var sure = confirm("<?php echo __('Current Gold Price(buy)', null, "goldTrading") ?>:" + currentGoldPrice + "\n<?php echo __('Paper Gold purchase quantity', null, "goldTrading") ?>:" + buyAmount + "(<?php echo __('g') ?>)\n<?php echo __('Trading Margin Required', null, "goldTrading") ?>:" + totalAmount + "\n<?php echo __('Confirm Purchase?', null, "goldTrading") ?>");
            if (sure) {
                form.submit();
            } else {
                $.unblockUI();
            }
        }
    });

    $("#btnBuy").button({
        icons: {
            primary: "ui-icon-cart"
        }
    });
    $('#txtBuyAmount').numeric({
        decimal:false
        , minValue:0
    });

    $("#goldTradingTabs").tabs().find(".ui-tabs-nav");

    datagridOpenTransaction = $("#datagridOpenTransaction").r9jasonDataTable({
        // online1DataTable extra params
        "idTr" : true, // assign <tr id='xxx'> from 1st columns array(aoColumns);
        "extraParam" : function(aoData){ // pass extra params to server
        },
        "reassignEvent" : function(){ // extra function for reassignEvent when JSON is back from server
            reassignDatagridOpenTransactionEventAttr();
        },

        // datatables params
        "bLengthChange": true,
        "bFilter": false,
        "bProcessing": true,
        "bServerSide": true,
        "bAutoWidth": false,
        "sAjaxSource": "/gold/openTransactionListing",
        "sPaginationType": "full_numbers",
        //"aaSorting": [[5,'desc']],
        "aoColumns": [
          { "sName" : "egold_id", "bVisible" : false,  "bSortable": true},
          { "sName" : "egold_id", "bSortable": true},
          { "sName" : "buy_price",  "bSortable": true},
          { "sName" : "buy_gram",  "bSortable": true},
          { "sName" : "marginUsed",  "bSortable": true},
          { "sName" : "created_on", "bVisible" : true,  "bSortable": true},
          { "sName" : "unrealizedProfitLoss",  "bSortable": true},
          { "sName" : "egold_id",  "bSortable": true,
            "fnRender": function ( oObj ) {
                <?php
                    if($validToBuyGold == true){
                ?>
                    if (oObj.aData[6]) {
                        var idx = 2;
                        $("#datagridOpenTransaction").data("openTransaction_" + oObj.aData[0], {
                                egold_id : oObj.aData[0]
                                , buy_price : oObj.aData[idx++]
                                , buy_gram : oObj.aData[idx++]
                                , marginUsed : oObj.aData[idx++]
                                , created_on : oObj.aData[idx++]
                                , unrealizedProfitLoss : oObj.aData[idx++]
                          });
                        return "<a id='sellLink' href='#' style='color:red'><?php echo __('Sell', null, "goldTrading") ?></a>";
                    } else {
                        return "";
                    }
                <?php
                    } else {
                        echo 'return ""';
                    }
                ?>
            }
          }
        ]
    });

    datagridBuyingHistory = $("#datagridBuyingHistory").r9jasonDataTable({
        // online1DataTable extra params
        "idTr" : true, // assign <tr id='xxx'> from 1st columns array(aoColumns);
        "extraParam" : function(aoData){ // pass extra params to server
        },
        "reassignEvent" : function(){ // extra function for reassignEvent when JSON is back from server
        },

        // datatables params
        "bLengthChange": true,
        "bFilter": false,
        "bProcessing": true,
        "bServerSide": true,
        "bAutoWidth": false,
        "sAjaxSource": "/gold/buyingHistoryListing",
        "sPaginationType": "full_numbers",
        "aaSorting": [[5,'desc']],
        "aoColumns": [
                      { "sName" : "egold_id", "bVisible" : false,  "bSortable": true},
                      { "sName" : "egold_id", "bSortable": true},
                      { "sName" : "buy_gram",  "bSortable": true},
                      { "sName" : "buy_price",  "bSortable": true},
                      { "sName" : "marginUsed",  "bSortable": true},
                      { "sName" : "created_on",  "bSortable": true}
        ]
    });

    datagridSellingHistory = $("#datagridSellingHistory").r9jasonDataTable({
        // online1DataTable extra params
        "idTr" : true, // assign <tr id='xxx'> from 1st columns array(aoColumns);
        "extraParam" : function(aoData){ // pass extra params to server
        },
        "reassignEvent" : function(){ // extra function for reassignEvent when JSON is back from server
        },

        // datatables params
        "bLengthChange": true,
        "bFilter": false,
        "bProcessing": true,
        "bServerSide": true,
        "bAutoWidth": false,
        "sAjaxSource": "/gold/sellingHistoryListing",
        "sPaginationType": "full_numbers",
        "aaSorting": [[6,'desc']],
        "aoColumns": [
                      { "sName" : "egold_id", "bVisible" : false,  "bSortable": true},
                      { "sName" : "egold_id", "bSortable": true},
                      { "sName" : "sell_gram",  "bSortable": true},
                      { "sName" : "sell_price",  "bSortable": true},
                      { "sName" : "marginUsed",  "bSortable": true},
                      { "sName" : "profit",  "bSortable": true},
                      { "sName" : "sell_date",  "bSortable": true}
        ]
    });

    $("#dgSellConfirmation").dialog("destroy");
    $("#dgSellConfirmation").dialog({
        autoOpen : false,
        modal : true,
        resizable : false,
        hide: 'clip',
        show: 'slide',
        height: 160,
        buttons: {
            "<?php echo __('Confirm') ?>": function() {
                waiting();
                $("#sellForm").submit();
                $(this).dialog('close');
            },
            "<?php echo __('Cancel') ?>": function() {
                $(this).dialog('close');
            }
        }
    });

    setInterval(function() {
        window.location = "<?php echo url_for("/gold/trading");?>";
    }, <?php echo Globals::REFRESH_GOLD_INTEVAL; ?>);
})

function reassignDatagridOpenTransactionEventAttr(){
	$("a[id=sellLink]").click(function(event){
		// stop event
		event.preventDefault();
		// event.target is <a> itself, parent() is <td>, while parent().parent() get <tr>
		// var id = alert("id = " +$(event.target).parent().parent().attr("id"));
		var id = $(event.target).parent().parent().attr("id");
        $("#goldId").val(id);

        $("#dgSellConfirmation").dialog("open");
	});
}
</script>

<div style="padding: 10px; top: 30px; width: 98%">
    <table>
        <?php if ($sf_flash->has('successMsg')): ?>
        <tr>
            <td>
                <div class="ui-widget">
                    <div style="margin-top: 20px; padding: 0 .7em;" class="ui-state-highlight ui-corner-all">
                        <p><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-info"></span>
                        <strong><?php echo $sf_flash->get('successMsg') ?></strong></p>
                    </div>
                </div>
            </td>
        </tr>
        <?php endif; ?>
        <tr>
            <td>
                <div class="portlet">
                    <div class="portlet-header"><?php echo __('Gold Chart') ?></div>
                    <div class="portlet-content">
                        <!-- <div id="placeholder" style="width:600px;height:300px"></div>-->
                        <div id="container" style="min-width: 400px; width:600px;height:300px; margin: 0 auto"></div>
                    </div>
                </div>
            </td>
            <td valign="top">
                <table width="98%" height="340" cellspacing="0" cellpadding="1" border="0" align="center" id="tableInfo">
                    <tbody>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Daily Trading Volume (Buy)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($goldTradingDto->getDailyTradingVolumeBuy(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('(Sell)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($goldTradingDto->getDailyTradingVolumeSell(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Monthly Trading Volume (Buy)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($goldTradingDto->getMonthlyTradingVolumeBuy(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('(Sell)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span><?php echo number_format($goldTradingDto->getMonthlyTradingVolumeSell(),0)?></span>
                            <span> <?php echo __('USD', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Paper Gold Quantity', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"> <span id="spanPaperGoldQuantity"><?php echo number_format($goldTradingDto->getPaperQuantity(),0)?></span>
                            <span id="MyGoldAccount1_Label3"> <?php echo __('g', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Average Price (Buy)', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B">
                                <span id="MyGoldAccount1_Label5">$</span>
                                <span id="spanAveragePriceBuy"><?php echo number_format($goldTradingDto->getAveragePriceBuy(),2)?></span>
                                <span id="MyGoldAccount1_Label4">/<?php echo __('g', null, "goldTrading") ?></span></font>
                        </td>
                    </tr>
                    <!--<tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php /*echo __('Unrealized Profit/Loss', null, "goldTrading") */?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B"><span
                                    id="MyGoldAccount1_Label6">$</span><span id="spanUnrealizedProfitLoss"><?php /*echo number_format($goldTradingDto->getUnrealizedProfitLoss(),2)*/?></span>
                            </font>
                        </td>
                    </tr>-->
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('Trading Point', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <font color="#61210B">
                                <span id="MyGoldAccount1_Label2">$</span>
                                <span id="spanEcash"><?php echo number_format($goldTradingDto->getTradingPoint(),2)?></span>
                                <input type="hidden" id="txtTradingPoint" value="<?php echo $goldTradingDto->getTradingPoint()?>">
                            </font>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 38%; white-space: nowrap;">
                            <strong><?php echo __('We buy', null, "goldTrading") ?>:</strong>
                        </td>
                        <td>
                            <span style="color:#61210B;">$</span>
                            <span style="color:#61210B;"><?php echo $goldTradingDto->getCompanyBuyGoldPrice()?></span>
                            <span style="color:#61210B;">/<?php echo __('g', null, "goldTrading") ?></span>&nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td valign="baseline" align="right">
                            <strong><?php echo __('We sell', null, "goldTrading") ?>:</strong>
                        </td>
                        <td valign="baseline" align="left">
                            <form action="/gold/buyGold" id="tradingForm" method="post">
                                <span style="color:#61210B;" id="Label4">$</span>
                                <span style="color:#61210B;" id="spanGoldSell"><?php echo $goldTradingDto->getCurrentGoldPrice()?></span>
                                <span style="color:#61210B;" id="Labelusdbuy">/<?php echo __('g', null, "goldTrading") ?></span>&nbsp;
                                <input type="text" style="width:80px;" id="txtBuyAmount" name="txtBuyAmount">
                                <span id="Labelgram"><strong><?php echo __('gram', null, "goldTrading") ?></strong></span>&nbsp;&nbsp;
                                    <?php
                                    if($validToBuyGold == true){
                                    ?>
                                        <button id="btnBuy"><?php echo __('Buy', null, "goldTrading") ?></button>
                                    <?php
                                        }
                                    ?>
                            </form>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </table>
</div>
<form action="/gold/sellGold" id="sellForm" method="post">
    <input type="hidden" name="goldId" id="goldId" value="">
</form>
<div id="goldTradingTabs">
    <ul>
        <li>
            <a href="#tabs-openTransactions"><?php echo __('Open Transactions', null, 'goldTrading') ?></a>
        </li>
        <li><a href="#tabs-buyingHistory"><?php echo __('Buying History', null, 'goldTrading') ?></a>
        </li>
        <li><a href="#tabs-sellingHistory"><?php echo __('Selling History', null, 'goldTrading') ?></a>
        </li>
    </ul>
    <div id="tabs-openTransactions">
        <table class="display" id="datagridOpenTransaction" border="0" width="90%">
            <thead>
            <tr>
                <th>id [hidden]</th>
                <th><?php echo __('Transaction ID', null, 'goldTrading') ?></th>
                <th><?php echo __('Price($/g)', null, 'goldTrading') ?></th>
                <th><?php echo __('Quantity(g)', null, 'goldTrading') ?></th>
                <th><?php echo __('Price(g)', null, 'goldTrading') ?></th>
                <th><?php echo __('Purchase Date', null, 'goldTrading') ?></th>
                <th><?php echo __('Unrealized Profit/Loss($)', null, 'goldTrading') ?></th>
                <th><?php echo __('Action', null, 'goldTrading') ?></th>
            </tr>
            </thead>
        </table>
    </div>
    <!--################    Buying History  ###################-->
    <div id="tabs-buyingHistory">
        <table class="display" id="datagridBuyingHistory" border="0" width="90%">
            <thead>
            <tr>
                <th>id [hidden]</th>
                <th><?php echo __('Transaction ID', null, 'goldTrading') ?></th>
                <th><?php echo __('Quantity(g)', null, 'goldTrading') ?></th>
                <th><?php echo __('Buy Price($/g)', null, 'goldTrading') ?></th>
                <th><?php echo __('Margin Used($)', null, 'goldTrading') ?></th>
                <th><?php echo __('Buy Date', null, 'goldTrading') ?></th>
            </tr>
            </thead>
        </table>
    </div>
    <!--##############  Selling History  #####################-->
    <div id="tabs-sellingHistory">
        <table class="display" id="datagridSellingHistory" border="0" width="90%">
            <thead>
            <tr>
                <th>id [hidden]</th>
                <th><?php echo __('Transaction ID', null, 'goldTrading') ?></th>
                <th><?php echo __('Quantity(g)', null, 'goldTrading') ?></th>
                <th><?php echo __('Sell Price($/g)', null, 'goldTrading') ?></th>
                <th><?php echo __('Margin Returned', null, 'goldTrading') ?></th>
                <th><?php echo __('Realised Profit/Loss', null, 'goldTrading') ?></th>
                <th><?php echo __('Sell Date', null, 'goldTrading') ?></th>
            </tr>
            </thead>
        </table>
    </div>
</div>

<div id="dgSellConfirmation" title="<?php echo __('Sell gold', null, 'goldTrading') ?>" style="display:none;">
    <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
        <?php echo __('Are you sure you want to sell gold?', null, 'goldTrading') ?>
        <span id="dgSellConfirmationSpanMsg"></span>
    </p>
</div>

<?php
$str = "";
$lowestXaxis = 0;
foreach ($goldPriceLogs as $goldPriceLog):
    if ($str != "") {
        $str .= ",";
    }
    $str .= $goldPriceLog['gold_price'];

    if ($lowestXaxis == 0) {
        $lowestXaxis = $goldPriceLog['gold_price'];
    } else if ($goldPriceLog['gold_price'] < $lowestXaxis) {
        $lowestXaxis = $goldPriceLog['gold_price'];
    }
endforeach;

$modulusValue = $lowestXaxis % 10;
$lowestXaxis = $lowestXaxis - $modulusValue;
?>
<script type="text/javascript">
    $(function () {
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                zoomType: 'x',
                spacingRight: 20
            },
            title: {
                text: 'Spot Gold'
            },
            subtitle: {
                text: document.ontouchstart === undefined ?
                    'Click and drag in the plot area to zoom in' :
                    'Drag your finger over the plot to zoom in'
            },
            xAxis: {
                type: 'datetime',
                maxZoom: 1 * 24 * 3600000, // fourteen days
                title: {
                    text: null
                }
            },
            yAxis: {
                title: {
                    text: 'per g'
                },
                min: <?php echo $lowestXaxis - 0.1; ?>,
                startOnTick: false,
                showFirstLabel: false
            },
            tooltip: {
                shared: true
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                area: {
                    fillColor: {
                        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
                        stops: [
                            [0, Highcharts.getOptions().colors[0]],
                            [1, 'rgba(2,0,0,0)']
                        ]
                    },
                    lineWidth: 1,
                    marker: {
                        enabled: false,
                        states: {
                            hover: {
                                enabled: true,
                                radius: 5
                            }
                        }
                    },
                    shadow: false,
                    states: {
                        hover: {
                            lineWidth: 1
                        }
                    }
                }
            },

            series: [{
                type: 'area',
                name: 'gold / per g',
                pointInterval: 60 * 1000,
                pointStart: Date.UTC(<?php echo date("Y") ?>, <?php echo date("m") -1 ?>, <?php echo date("j") ?>),
                data: [
                    <?php echo $str; ?>
                ]
            }]
        });
    });
});
</script>